package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.MinistryMapper;
import com.sumainfor.pc.market.dao.RdHousingInfoMapper;
import com.sumainfor.pc.market.dao.RdSubletApplyMapper;
import com.sumainfor.pc.market.dao.UtilsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 *转租申请
 */
@Service
public class RdSubletApplyService {
    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdWorderInfoService.class);// 日志

    @Autowired
    private RdSubletApplyMapper rdSubletApplyMapper;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private RdHousingInfoMapper rdHousingInfoMapper;


    /**
     *查询转租的申请列表
     */
    public List<Map<String,Object>> getSubletApplyList(Map<String, Object> params){
        return rdSubletApplyMapper.getSubletApplyList(params);
    }
    /**
     * 查询转租的申请列表总数
     */
    public Integer getSubletApplyListCount(Map<String,Object> params){
        return rdSubletApplyMapper.getSubletApplyListCount(params);
    }
    /**
     * 修改转租申请状态为已上架
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateSubletApply(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("SubId")==null || params.get("HouInfoId")==null){
                    return result.putFailed("参数不正确");
                }
                params.put("SubState",1);//申请上架状态（0 待上架 1已上架）
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                Integer count = rdSubletApplyMapper.updateSubletApply(params);
                if (count>0){
                    Map<String,Object> map=new HashMap<String,Object>();
                    map.put("Sublease",1);//当前房源是否转租  0.否  1.是
                    map.put("HouInfoId",params.get("HouInfoId"));//房源详表编号
                    map.put("updtm",params.get("updtm"));
                    map.put("updterm",params.get("updterm"));
                    map.put("updby",params.get("updby"));
                    map.put("updfnc",params.get("updfnc"));
                    Integer houCount=rdHousingInfoMapper.updateHousingHouInfo(map);
                    if (houCount>0){
                        result.putSuccess("操作成功");
                    }else{
                        result.putFailed("服务器繁忙");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 新增加转租申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addSubletApply(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("HouId")==null || params.get("HouInfoId")==null
                        || params.get("PaId")==null || params.get("TenId")==null || params.get("MoveTime")==null
                        || params.get("LookTime")==null){
                    return result.putFailed("参数不正确");
                }
                //转租编号
                String UUID="";
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "SubId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_sublet_apply");
                }});
                if(uuid!=null){
                    int number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("su",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("su",0);
                }
                params.put("SubId",UUID);//转租转租申请编号
                params.put("SubState",0);//申请上架状态（0 待上架 1已上架）
                params.put("by", "auto");//操作人
                params.put("term", "1");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                Integer count = rdSubletApplyMapper.addSubletApply(params);
                if (count>0){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 租客取消转租申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateCancelApply(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("SubId")==null ||params.get("HouInfoId")==null){
                    return result.putFailed("参数不正确");
                }
                params.put("SubState",2);//申请上架状态（0 待上架 1已上架 2已取消）
                params.put("by", "auto");//操作人
                params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                Integer count = rdSubletApplyMapper.updateCancelApply(params);
                if (count>0){
                    Map<String,Object> map=new HashMap<String,Object>();
                    map.put("Sublease",0);//当前房源是否转租  0.否  1.是
                    map.put("HouInfoId",params.get("HouInfoId"));//房源详表编号
                    map.put("updtm",params.get("updtm"));
                    map.put("updterm",params.get("updterm"));
                    map.put("updby",params.get("updby"));
                    map.put("updfnc",params.get("updfnc"));
                    Integer houCount=rdHousingInfoMapper.updateHousingHouInfo(map);
                    if (houCount>0){
                        result.putSuccess("操作成功");
                    }else{
                        result.putFailed("服务器繁忙");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     *查询是否已经发起过转租申请
     */
    public JsonResult getSubApplyCount(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("PaId")==null ){
            return result.putFailed("参数不正确");
        }
        Map<String,Object> map=rdSubletApplyMapper.getSubApplyCount(params);
        if (map!=null){
            result.put(map);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
}
